package hai.wom.org.qyer_destination.utils;

import android.os.AsyncTask;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import hai.wom.org.qyer_destination.callback.ICallback;

/**
 * Created by Administrator on 2017/1/12 0012.
 */

public class HttpUtils extends AsyncTask<String,Void,byte[]> {
   private ICallback callback;

    public HttpUtils(ICallback callback) {
        this.callback = callback;
    }

    @Override
    protected byte[] doInBackground(String... params) {
        ByteArrayOutputStream baos=null;
        try {
            URL url=new URL(params[0]);
            HttpURLConnection connection= (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            if (connection.getResponseCode()==200){
                InputStream inputStream=connection.getInputStream();
                baos=new ByteArrayOutputStream();
                int len=0;
                byte[] buffer=new byte[1024*8];
                while ((len=inputStream.read(buffer))!=-1){
                    baos.write(buffer,0,len);
                    baos.flush();
                }
                return baos.toByteArray();

            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (baos!=null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(byte[] bytes) {
        super.onPostExecute(bytes);
        if (bytes!=null){
            callback.getData(new String(bytes));
        }
    }
}
